﻿using System;
using System.Linq;
using QDT.Common;
using QDT.Common.Finance;
using QDT.Core;
using QDT.Core.Experience;
using QDT.Core.Members;
using QDT.P2B.Domain.Config;
using QDT.P2B.Domain.Messages;

namespace QDT.Services.Experience
{
    public class ExpService : ServiceBase, IExpService
    {
        private static readonly object _asnyLock = new object();

        public ExpCredit Bid(int userid, int projectid, decimal money)
        {
            lock (_asnyLock)
            {
                var user = DbProvider.D<User>().Where(x => x.ID == userid && x.IsEffect && !x.IsDelete).ToList().FirstOrDefault();
                if (user == null) throw new Exception("用户不存在或者已经被删除");
                var project = DbProvider.GetByID<ExpProject>(projectid);
                if (project == null) throw new Exception("项目不存在");

                DbProvider.Refresh(user.UserAccount);
                DbProvider.Refresh(project);
                
                return Bid(user, project, money);
            }
        }

        public void Refund(int projectId)
        {
            var project = DbProvider.GetByID<ExpProject>(projectId);

            if (project == null) throw new Exception("无效的体验宝项目");

            if (project.Status != 2) throw new Exception("不是还款中的项目");

            if (!project.RepayEndTime.HasValue || project.RepayEndTime.Value.Date > DateTime.Now) throw new Exception("未到还款时间");

            project.Status = 3;
            project.IsRepay = true;

            //获得所有的债权人
            IQueryable<ExpCredit> credits = DbProvider.D<ExpCredit>().Where(x => x.ExpProjectId == projectId);

            foreach (var credit in credits.Where(credit => !credit.IsRepay))
            {
                credit.IsRepay = true;
                project.RepayMoney += credit.Earning;

                var user = DbProvider.GetByID<User>(credit.UserId);

                var remark = "体验标:{0},返还利息：{1}".FormatWith(project.ID, credit.Earning.ToString("0.00"));
                var userLog = user.Transaction(UserTransLog.TradeType.RecoverInterest, credit.Earning, "系统", remark);

                //线下和路人不发短信
//                if (user.MobilePassed && user.GroupID == 3 && SettingManager.Get<MessageConfig>().SmsOpen)
                if (user.MobilePassed && SettingManager.Get<MessageConfig>().SmsOpen)
                {
                    var msg = new MsgQueueFactory().CreateRepayMsg(user, credit.Earning, projectId);
                    msg.Content = "亲爱的众禧贷用户,本期回款{0}元，体验宝项目编号为:{1}".FormatWith(project.ID, credit.Earning.ToString("0.00"));
                    DbProvider.Add(msg);
                }
                DbProvider.Add(userLog);
            }

            DbProvider.SaveChanges();
        }

        public ExpCredit Bid(User user, ExpProject project, decimal money)
        {

            if (money <= 0) throw new Exception("投资金额不能是负数和0");
            if (project.Status != 1) throw new Exception("项目状态异常");
            if (project.NeedMoney < money) throw new Exception("项目可投余额不足");
            if (user.UserAccount.ExpMoney < money) throw new Exception("用户余额不足");
            if (!user.IsLender || user.IsDelete || !user.IsEffect) throw new Exception("用户异常");
            if (project.MinLoanMoney > money && project.NeedMoney > project.MinLoanMoney) throw new Exception("小于最低投资金额");
            if (project.MaxLoanMoney < money) throw new Exception("大于最高投资金额");
            if (project.StartTime > DateTime.Now) throw new Exception("未到开始时间，不能投资 !");
            if (DbProvider.D<ExpCredit>().Any(x=>x.UserId==user.ID && x.ExpProjectId==project.ID)) throw new Exception("已投资该体验宝，不能重复投资 !");

            var credit = new ExpCredit
            {
                ExpProjectId = project.ID,
                UserId = user.ID,
                UserName = user.UserName,
                Money = money,
                CreateTime = DateTime.Now,
                Earning = InterestAlgorithm.DailyInterest(project.Days, money, project.Rate/100),
            };

            project.LoadMoney += money;

            if (project.NeedMoney == 0)
            {
                project.Status = 2;
                project.RepayStartTime = DateTime.Now;
                project.RepayEndTime = DateTime.Now.Date.AddDays(project.Days);
            }

            user.UserAccount.ExpMoney -= money;

            string msg = "投资了体验宝项目, 体验金扣除：{0}".FormatWith(money.ToString("0.00"));
            var userLog = user.FreezeMoney(UserTransLog.TradeType.Other, 0, "", msg);

            DbProvider.Add(credit);
            DbProvider.Add(userLog);
            DbProvider.SaveChanges();

            return credit;
        }

    }
}
